/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
        {
			name: 'step_filter',
			title: 'step过滤',
			type: 'LineEdit'
		},
        {
			name : 'rout',
			title : '外形层',
			type : 'LineEdit',
			property : {tool_tip : '外形层，默认是gko'},
		},
		{
			name : 'npth_resize',
			title : 'NP涨大值',
			type : 'LineEdit',
			property : {tool_tip : 'NP涨大值,默认是300um'},
		},
		{
			name : 'dest_step',
			title : '外形涨大值',
			type : 'LineEdit',
			property : {tool_tip : '外形涨大值,默认是200um'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        },
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-26 Carver
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 内外层处理 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> NP涨大值、外形涨大值、自动保存 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>内外层处理");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

var drill_name = 'drl';
var aide_layer = 'np_tmp3';  //辅助层

try {
	var par = PAR;
	var default_par = {
        step_filter:'net.+',
        step2:"net",
        rout:"ol",
		npth_resize: "300um",
		rout_resize: "200um",
        auto_save: "No",
        units: 'mm',
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
    }
    var out_line_name = par.rout;
    
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    
    var matrix = GEN.getMatrix({job:job})

    var positive_layer = [];  //内层正片层
    var negative_layer = Object.keys(matrix).reduce(function(a,b){  //内层负片层
        if(matrix[b].context == "board" && /signal|power/.test(matrix[b].layer_type)){
            if(matrix[b].side == "inner" || matrix[b].side == "top" || matrix[b].side == "bottom"){
                if(matrix[b].polarity == "negative"){
                    a.push(b)
                }else{
                    positive_layer.push(b)
                }
            } 
        }
        return a;
    },[])
    var stepList = GEN.getStepList({job:job})
	stepList = stepList.filter(function(step){
		var reg = new RegExp(par.step_filter,"ig")
		return reg.test(step)
    })
    if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
    stepList.forEach(function(step){
        GEN.openStep({job:job,name:step})

        //料号初始化
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
		//操作模式初始化
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units });  ////单位初始化
        GEN.zoomHome();  //窗口显示回到原始位置
        

        // 从drill层里面过滤np属性的孔并复制到辅助层np_tmp3上
        GEN.workLayer({name:drill_name,display_number:1,clear_before:'yes'})
        GEN.selectByFilter({ 'attribute':[{attribute:'.drill',option:'non_plated'}] })
        if(GEN.getSelectCount() > 0){  // 要判断大于0，否则会默认copy整层
            GEN.selCopyOther({ 
                'dest':'layer_name',
                'target_layer': aide_layer,  
                'invert':'no',
                'dx':0,
                'dy':0,
                'size':0
            })
        }
        
        GEN.clearLayers();  //清除层显示
        GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响

        // 设置内层负片层为影响层
        if(negative_layer.length > 0) {
            GEN.affectedLayer({affected:'yes', layer:negative_layer, clear_before:'yes'});
            // 删除所有花盘
            GEN.selectByFilter({'include_syms':'th*\;i*','profile':'all'})
        }
        if(GEN.getSelectCount() > 0){ 
            GEN.selDelete();
        }

        if(GEN.isLayerExists({job:job, layer:aide_layer})){
            if(negative_layer.length>0){
                GEN.workLayer({name:aide_layer,display_number:1,clear_before:'yes'})  
                GEN.affectedLayer({affected:'yes', layer:negative_layer, clear_before:'no'}); 
                // 将np_tmp3上的数据resize 300um copy到影响层
                GEN.selCopyOther({
                    'dest':'affected_layers',
                    'target_layer': '',  
                    'invert':'no',
                    'dx':0,
                    'dy':0,
                    'size':300,  
                })
            }
            if(positive_layer.length>0){
                GEN.workLayer({name:aide_layer,display_number:1,clear_before:'yes'})  
                GEN.affectedLayer({affected:'yes', layer:positive_layer, clear_before:'no'}); 
                // 将np_tmp3上的数据resize 300um copy到影响层
                GEN.selCopyOther({
                    'dest':'affected_layers',
                    'target_layer': '',  
                    'invert':'yes',
                    'dx':0,
                    'dy':0,
                    'size':300,  
                })
            }
        }

        if(GEN.isLayerExists({job:job, layer:out_line_name})){
            if(negative_layer.length>0){
                // 外形层gko上的数据resize 200um copy到影响层
                GEN.workLayer({name:out_line_name,display_number:1,clear_before:'yes'})
                GEN.affectedLayer({affected:'yes', layer:negative_layer, clear_before:'no'});
                GEN.selCopyOther({
                    'dest':'affected_layers',
                    'target_layer': '',  
                    'invert':'no',
                    'dx':0,
                    'dy':0,
                    'size':200, 
                })
            }
            if(positive_layer.length>0){
                // 将外形层上的数据resize 200um并改变极性copy到影响层；
                GEN.workLayer({name:out_line_name,display_number:1,clear_before:'yes'})
                GEN.affectedLayer({affected:'yes', layer:positive_layer, clear_before:'no'});
                GEN.selCopyOther({
                    'dest':'affected_layers',
                    'target_layer': '',  
                    'invert':'yes',
                    'dx':0,
                    'dy':0,
                    'size':200, 
                })
            }
        }

        // 取消影响层并删除辅助层np_tmp3
        GEN.clearLayers();
        GEN.affectedLayer({ mode: 'all', affected: 'no' });

	})
	
	if(GEN.isLayerExists({job:job, layer:aide_layer})){  //删除辅助层np_tmp3
		GEN.deleteLayer({job:job, layer:[aide_layer]});
	}
    
	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}   
} catch (e) {
    IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}